import prisma from '../config/prisma';
import {
  Question,
  QuestionDetail,
  CreateQuestionRequest,
  UpdateQuestionRequest,
  QuestionQueryParams,
  QuestionListResponse,
} from '../models/Question';
import { generateTimestampNumericUUID } from '../utils/uuid';
import { QuestionContentService } from './question-content-service';

export class QuestionService {
  // 获取问题列表（支持分页和筛选）
  static async getQuestions(
    params: QuestionQueryParams
  ): Promise<QuestionListResponse> {
    const {
      page = 1,
      limit = 10,
      status,
      priority,
      userId,
      search,
      sortBy = 'createdAt',
      sortOrder = 'desc',
    } = params;

    const skip = (page - 1) * limit;

    // 构建查询条件
    const where: any = {};

    if (status) {
      where.status = status;
    }

    if (priority) {
      where.priority = priority;
    }

    if (userId) {
      where.userId = userId;
    }

    if (search) {
      where.title = {
        contains: search,
        mode: 'insensitive',
      };
    }

    // 获取总数
    const total = await prisma.question.count({ where });

    // 获取问题列表
    const questions = await prisma.question.findMany({
      where,
      skip,
      take: limit,
      orderBy: {
        [sortBy]: sortOrder,
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            avatar: true,
          },
        },
      },
    });

    const totalPages = Math.ceil(total / limit);

    return {
      questions: questions as unknown as Question[],
      total,
      page,
      limit,
      totalPages,
    };
  }

  // 根据ID获取问题详情
  static async getQuestionById(id: string): Promise<QuestionDetail | null> {
    const question = await prisma.question.findUnique({
      where: { id },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            avatar: true,
          },
        },
      },
    });

    if (!question) {
      return null;
    }

    // 从MongoDB获取问题内容和附件
    const questionContentData = await QuestionContentService.getQuestionContent(question.contentId);
    
    return {
      ...question,
      content: questionContentData?.content || '',
      attachments: questionContentData?.attachments || [],
    } as unknown as QuestionDetail;
  }

  // 创建问题
  static async createQuestion(
    questionData: CreateQuestionRequest
  ): Promise<QuestionDetail> {
    const questionId = generateTimestampNumericUUID();

    // 首先将内容和附件保存到MongoDB
    const contentId = await QuestionContentService.createQuestionContent(
      questionData.content,
      questionData.attachments
    );

    // 然后将问题基本信息保存到PostgreSQL
    const question = await prisma.question.create({
      data: {
        id: questionId,
        title: questionData.title,
        contentId: contentId,
        userId: questionData.userId,
        status: questionData.status || 'pending',
        priority: questionData.priority || 'medium',
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            avatar: true,
          },
        },
      },
    });

    return {
      ...question,
      content: questionData.content,
      attachments: questionData.attachments || [],
    } as unknown as QuestionDetail;
  }

  // 更新问题
  static async updateQuestion(
    questionData: UpdateQuestionRequest
  ): Promise<QuestionDetail | null> {
    // 获取当前问题信息
    const currentQuestion = await prisma.question.findUnique({
      where: { id: questionData.id },
    });

    if (!currentQuestion) {
      return null;
    }

    // 如果需要更新内容或附件，更新MongoDB
    if (questionData.content !== undefined || questionData.attachments !== undefined) {
      await QuestionContentService.updateQuestionContent(
        currentQuestion.contentId,
        questionData.content,
        questionData.attachments
      );
    }

    // 更新PostgreSQL中的基本信息
    const { id, content, attachments, ...updateFields } = questionData;

    const question = await prisma.question.update({
      where: { id },
      data: updateFields,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            avatar: true,
          },
        },
      },
    });

    // 获取更新后的内容
    const updatedContentData = await QuestionContentService.getQuestionContent(question.contentId);

    return {
      ...question,
      content: updatedContentData?.content || '',
      attachments: updatedContentData?.attachments || [],
    } as unknown as QuestionDetail;
  }

  // 删除问题
  static async deleteQuestion(id: string): Promise<boolean> {
    try {
      // 先获取问题信息以获取contentId
      const question = await prisma.question.findUnique({
        where: { id },
        select: { contentId: true },
      });

      if (!question) {
        return false;
      }

      // 删除MongoDB中的内容
      if (question.contentId) {
        await QuestionContentService.deleteQuestionContent(question.contentId);
      }

      // 删除PostgreSQL中的问题记录
      await prisma.question.delete({ where: { id } });
      return true;
    } catch (error) {
      console.error('Error deleting question:', error);
      return false;
    }
  }

  // 增加浏览次数
  static async incrementViewCount(id: string): Promise<void> {
    await prisma.question.update({
      where: { id },
      data: {
        viewCount: {
          increment: 1,
        },
      },
    });
  }

  // 增加点赞数
  static async incrementLikeCount(id: string): Promise<void> {
    await prisma.question.update({
      where: { id },
      data: {
        likeCount: {
          increment: 1,
        },
      },
    });
  }

  // 减少点赞数
  static async decrementLikeCount(id: string): Promise<void> {
    await prisma.question.update({
      where: { id },
      data: {
        likeCount: {
          decrement: 1,
        },
      },
    });
  }

  // 更新答案数量
  static async updateAnswerCount(id: string, count: number): Promise<void> {
    await prisma.question.update({
      where: { id },
      data: {
        answerCount: count,
      },
    });
  }

  // 获取用户的问题列表
  static async getUserQuestions(
    userId: string,
    params: QuestionQueryParams
  ): Promise<QuestionListResponse> {
    return this.getQuestions({ ...params, userId });
  }

  // 获取热门问题（按浏览量排序）
  static async getPopularQuestions(limit: number = 10): Promise<Question[]> {
    const questions = await prisma.question.findMany({
      take: limit,
      orderBy: {
        viewCount: 'desc',
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            avatar: true,
          },
        },
      },
    });

    return questions as unknown as Question[];
  }

  // 获取最新问题
  static async getLatestQuestions(limit: number = 10): Promise<Question[]> {
    const questions = await prisma.question.findMany({
      take: limit,
      orderBy: {
        createdAt: 'desc',
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            avatar: true,
          },
        },
      },
    });

    return questions as unknown as Question[];
  }
}
